#pragma once
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <functional>
#include <pthread.h>

enum Err
{
    USAGE_ERR = 1,
    SOCKET_ERR,
    BIND_ERR,
    SEND_ERR
};

class Client
{
public:
    Client(const std::string &serverip, const uint16_t &serverport)
        : _serverip(serverip), _serverport(serverport), _sockfd(-1) {}

    void initClient()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            std::cerr << "socket error" << errno << ":" << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        std::cout << "socket success: " << " : " << _sockfd << std::endl;
        // 客户端不需要显示的bind，在sendto的时候由os自动完成
    }

    static void *readMessage(void *args)
    {
        int sockfd = *(static_cast<int *>(args));
        // 线程自己进行分离，结束时自动回收资源
        pthread_detach(pthread_self());
        while (true)
        {
            char buffer[1024];
            // 用于填充返回来的服务器的ip和端口
            struct sockaddr_in client_recv;
            socklen_t len = sizeof(client_recv);
            int n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client_recv, &len);
            if (n >= 0)
                buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    void run()
    {
        // 创建一个线程用来接收服务器转发来的消息
        pthread_create(&_reader, nullptr, readMessage, (void *)&_sockfd);
        struct sockaddr_in server;
        // memset(&server, 0, sizeof(server));
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());

        std::string message;
        char cmd[1024];
        while (true)
        {
            fgets(cmd, sizeof(cmd), stdin);
            cmd[strlen(cmd) - 1] = 0;//清除最后按下的回车操作
            message = cmd; // 为了不改变下面的操作，这里直接将cmd中的内容赋值给message就可以

            ssize_t n = sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
            if (n == -1)
            {
                std::cerr << "send error " << errno << ":" << strerror(errno) << std::endl;
                exit(SEND_ERR);
            }
        }
    }

    ~Client() {};

private:
    int _sockfd;
    std::string _serverip;
    uint16_t _serverport;
    pthread_t _reader;
};